package com.opencee.cloud.uaa.handler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 支持重定向附带参数
 *
 * @author yadu
 */
public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

    /**
     * 附带参数重定向
     */
    private boolean redirectWithParams = true;
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    public boolean isRedirectWithParams() {
        return redirectWithParams;
    }

    public void setRedirectWithParams(boolean redirectWithParams) {
        this.redirectWithParams = redirectWithParams;
    }

    public CustomAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String redirectUrl = null;
        if (redirectWithParams) {
            redirectUrl = this.buildRedirectUrlWithParams(request);
            redirectStrategy.sendRedirect(request, response, redirectUrl);
        } else {
            super.commence(request, response, authException);
        }
    }

    protected String buildRedirectUrlWithParams(HttpServletRequest request) throws IOException, ServletException {
        int serverPort = this.getPortResolver().getServerPort(request);
        String scheme = request.getScheme();
        RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
        urlBuilder.setScheme(scheme);
        urlBuilder.setServerName(request.getServerName());
        urlBuilder.setPort(serverPort);
        urlBuilder.setContextPath(request.getContextPath());
        urlBuilder.setPathInfo(getLoginFormUrl());
        urlBuilder.setQuery(request.getQueryString());
        return urlBuilder.getUrl();
    }
}
